package com.test.mqtt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Scanner;

@Component
public class MqttCliRunner implements CommandLineRunner {

    private final MqttGateway mqttGateway;

    @Autowired
    public MqttCliRunner(MqttGateway mqttGateway) {
        this.mqttGateway = mqttGateway;
    }

    @Override
    public void run(String... args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println();
        System.out.println("           Program notes         ");
        System.out.println("*---------------------------------*");
        System.out.println('|' + " Enter 'exit' to stop the INPUT. " + '|');
        System.out.println('|' + " Enter 'change' to change topic. " + '|');
        System.out.println("*---------------------------------*");
        System.out.print("Enter topic: ");
        String topic = scanner.nextLine();
        System.out.print("Enter messages to MQTT: ");

        while (true) {
            String message = scanner.nextLine();
            if ("exit".equalsIgnoreCase(message)) {
                break;
            }else if("change".equalsIgnoreCase(message)){
                System.out.println("Enter topic: ");
                topic = scanner.nextLine();
                System.out.print("Enter message: ");
                message = scanner.nextLine();
            }

            mqttGateway.sendToMqtt(topic, 1, message);
            System.out.println("Message sent to topic: " + topic + "  successfully!");
        }
        scanner.close();
    }
}